//
// Created by fh on 2021/6/1.
//

#include "LinkStack.h"

/* 链栈生成和初始化 */
LinkStack *LinkStackCreateAndInit() {
    LinkStack *l = (LinkStack *) malloc(sizeof(LinkStack));
    l->top = NULL;
    l->count = 0;
    return l;
}

/* 插入元素e为新的栈顶元素 */
Status LinkStackPush(LinkStack *s,int e) {
    StackNode *node = (StackNode *) malloc(sizeof(StackNode));
    if (node == NULL) {
        return ERROR; /*如果内存分配失败就返回错误*/
    }
    node->data = e;
    node->next = s->top; /*把当前的栈顶元素赋值给新结点的直接后继*/
    s->top = node;/*将新的结点s赋值给栈顶指针*/
    s->count++;
    return OK;
}

/* 若栈不空，则删除s的栈顶元素，用e返回其值 */
Status LinkStackPop(LinkStack *s,int *e) {
    if (s->top == NULL) {
        return ERROR;/*栈空的话直接返回错误*/
    }
    StackNode *node = s->top;/*记住要释放的结点*/
    *e = node->data;
    s->top = node->next;
    free(node);
    node = NULL;
    s->count--;
    return OK;
}

/* 遍历链栈 */
Status LinkStackDisplay(LinkStack *s) {
    printf("遍历链栈:");
    StackNode *p = s->top;
    while (p != NULL) {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
    return OK;
}

/* 测试demo */
void linkStackTestDemo() {
    // 演示结构体定义
    // 1.使用定义
    StackNode node0 = {
            1,
            NULL
    };
    // 2.使用结构标签
    struct StackNode node1 = {
            2,
            NULL
    };
    printf("--------------------------- 链栈进栈 ------------------------\n");
    LinkStack *l = (LinkStack *) malloc(sizeof(LinkStack));
    l->top = NULL;
    l->count = 0;
    LinkStackDisplay(l);

    Status result = LinkStackPush(l,1);
    printf("LinkStackPush result: %d\n",result);
    LinkStackDisplay(l);

    result = LinkStackPush(l,2);
    printf("LinkStackPush result: %d\n",result);
    LinkStackDisplay(l);

    result = LinkStackPush(l,5);
    printf("LinkStackPush result: %d\n",result);
    LinkStackDisplay(l);

    result = LinkStackPush(l,6);
    printf("LinkStackPush result: %d\n",result);
    LinkStackDisplay(l);

    result = LinkStackPush(l,9);
    printf("LinkStackPush result: %d\n",result);
    LinkStackDisplay(l);

    printf("--------------------------- 链栈出栈 ------------------------\n");
    int a = 0;
    result = LinkStackPop(l,&a);
    printf("LinkStackPop result: %d\n",result);
    printf("a: %d\n",a);
    LinkStackDisplay(l);
}

